<?php
/**
 * Created by PhpStorm.
 * User: stupboy
 * Date: 2018/5/25
 * Time: 17:03
 * Mail:87658989@qq.com
 */

namespace app\adminapi\model;
use app\adminapi\filter\DriverList;
use app\base\exception\RecordHasExistException;
use app\base\exception\RecordNotFoundException;
use think\exception\DbException;
use traits\model\SoftDelete;

class Driver extends Common
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';
    /**
     * 司机列表
     * @param string $field
     * @param array $where
     * @param int $page
     * @param int $num
     * @return array
     */
    public function getDriverList($field='*',$where=[],$page=1,$num=10){
        $filter = new DriverList();
        $filter->analyzeField();
        list(,$msg) = $filter->checkField($field);
        list(,$whereMsg) = $filter->checkWhere($where);

        $buildQuery = function($query) use ($whereMsg) {
            self::authCompanyQuery($query, $whereMsg, 'a.company_id');
        };

        try{
            $data['data'] = $this->alias('a')
                ->join('company b','a.company_id = b.company_id','left')
                ->join('car c','a.car_id = c.car_id','left')
                ->where($buildQuery)
                ->page($page,$num)
                ->field($msg)
                ->select();
        }catch (DbException $e){
            $data['data'] = [];
        }
        $data['data']  = $filter->checkData($data['data']);
        $data['count'] = $this->alias('a')
            ->join('company b','a.company_id = b.company_id','left')
            ->join('car c','a.car_id = c.car_id','left')
            ->where($buildQuery)
            ->field($msg)
            ->count();
        $data['description'] = $filter->title;
        $data['fields']      = $filter->fieldTitle;
        return [1,$data];
    }

    /**
     * 新增或更新司机
     * @param $params
     * @return $this|false|int
     * @throws DbException
     * @throws \app\base\exception\RecordNotFoundException
     * @throws \app\base\exception\RecordHasExistException
     */
    public function createOrUpdate($params) {
        $session = (new User())->getLoginUser();
        if(isset($params['driver_id'])) {
            $where = ['driver_id' => $params['driver_id']];
            $buildQuery = function($query) use ($where) {
                self::authCompanyQuery($query, $where, 'a.company_id');
            };

            $driver = self::get($buildQuery);
            if(!$driver) {
                throw new RecordNotFoundException();
            }
        }elseif(!self::isSuperAdmin($session) && $session['user']['company_id']) {
            $params['company_id'] = $session['user']['company_id'];
        }

        // 验证单位是否存在
        $this->addRelativeFields( $params, 'app\adminapi\model\Company', $params['company_id'],  [], '关联单位不存在');
        if(isset($params['driver_id'])) {
            return $this->isUpdate(true)->save($params);
        }
        $whereOr = [];
        $params['user_id'] >0 && $whereOr['user_id'] = $params['user_id'];
        $has = $this->where('phone',$params['phone'])->whereOr($whereOr)->whereNull('delete_time')->find();
        if(!empty($has)) throw new RecordHasExistException();
        // 校验用户id 用户id为0的情况下自动生成账号
        $params['user_id'] = (new User())->autoCreate( $params['phone'] ,$params['user_id'] , 5);
        $this->data($params)->save();
        return $this;
    }
}